﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Net;

namespace RightControl.Common {
    public class ImageConvert {

        //图片 转为 base64编码的文本
        public static string ToBase64String(string fileUrl) {
            //WebClient wb = new WebClient();
            try {

                if (string.IsNullOrEmpty(fileUrl)) {
                    return "";
                }
         
                HttpHelper httphelper = new HttpHelper();
                HttpItem httpItem = new HttpItem();
                httpItem.ResultType = HttpResultType.Byte;
                httpItem.URL = fileUrl;
                httpItem.SecurityProtocolType = SecurityProtocolType.Tls12;

                HttpResult result = httphelper.GetHtml(httpItem);
                if (result != null) {
                    return Convert.ToBase64String(result.ResultByte);
                }
                //byte[] imgBytes = wb.DownloadData(fileUrl);
                //System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                //        delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                //                     System.Security.Cryptography.X509Certificates.X509Chain chain,
                //                     System.Net.Security.SslPolicyErrors sslPolicyErrors) {
                //            return true; // **** Always accept
                //  };

                //return Convert.ToBase64String(imgBytes);

                return "";
            }
            catch (Exception ex) {
                return "";
            }
            finally {
                //wb.Dispose();
              
            }
        }

        /// <summary>
        /// 将Base64字符串转换为图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private static void ToImage(object sender, EventArgs e) {
        //    string base64 = this.richTextBox.Text;
        //    byte[] bytes = Convert.FromBase64String(base64);
        //    MemoryStream memStream = new MemoryStream(bytes);
        //    BinaryFormatter binFormatter = new BinaryFormatter();
        //    Image img = (Image)binFormatter.Deserialize(memStream);
        //    this.pictureBox.Image = img;
        //}

        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量（数字越小压缩率越高）1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true) {
            //如果是第一次调用，原始图像的大小小于要压缩的大小，则直接复制文件，并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);
            if (sfsc == true && firstFileInfo.Length < size * 1024) {
                firstFileInfo.CopyTo(dFile);
                return true;
            }
            Image iSource = Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth) {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode =SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++) {
                    if (arrayICI[x].FormatDescription.Equals("JPEG")) {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null) {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size) {
                        flag = flag - 10;
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch {
                return false;
            }
            finally {
                iSource.Dispose();
                ob.Dispose();
            }
        }

        /**
         * 无损缩放图片(获取超过1000*1000的图)
         * bitmap 需要缩放的图片
         * w 需要缩放的宽度
         * h 需要缩放的高度
         * */
        public static Bitmap TBScaleBitmap(Bitmap bitmap, int w, int h, string mode) {
         
            int x = 0;
            int y = 0;
            int ow = bitmap.Width;
            int oh = bitmap.Height;
            if (ow > 999) {
                if (oh > 999) {
                    return bitmap;
                }
                else {
                    mode = "H";
                }
            }
            else {
                mode = oh > 999 ? "W" : (ow < oh ? "W" : "H");
            }

            int towidth = w;
            int toheight = h;

            switch (mode) {
                case "HW":  //指定高宽缩放（可能变形）                
                    break;
                case "W":   //指定宽，高按比例                    
                    toheight = bitmap.Height * w / bitmap.Width;
                    break;
                case "H":   //指定高，宽按比例
                    towidth = bitmap.Width * h / bitmap.Height;
                    break;
                case "Cut": //指定高宽裁减（不变形）                
                    if ((double)bitmap.Width / (double)bitmap.Height > (double)towidth / (double)toheight) {
                        oh = bitmap.Height;
                        ow = bitmap.Height * towidth / toheight;
                        y = 0;
                        x = (bitmap.Width - ow) / 2;
                    }
                    else {
                        ow = bitmap.Width;
                        oh = bitmap.Width * h / towidth;
                        x = 0;
                        y = (bitmap.Height - oh) / 2;
                    }
                    break;
                case "MaxHW"://最大宽高比例缩放，比如原100*50->50*30，则结果是50*25
                    var rmaxhw_d1w = bitmap.Width * 1.0 / w;
                    var rmaxhw_d2h = bitmap.Height * 1.0 / h;
                    if (rmaxhw_d1w > rmaxhw_d2h) {
                        if (rmaxhw_d1w <= 1) {
                            towidth = bitmap.Width; h = bitmap.Height;
                            goto case "HW";
                        }
                        towidth = w;
                        goto case "W";
                    }
                    if (rmaxhw_d2h <= 1) {
                        towidth = bitmap.Width; h = bitmap.Height;
                        goto case "HW";
                    }
                    toheight = h;
                    goto case "H";
                default:
                    break;
            }
            Bitmap map = new Bitmap(towidth, toheight);

            Graphics gra = Graphics.FromImage(map);
            gra.Clear(Color.Transparent);//清空画布并以透明背景色填充
            gra.SmoothingMode = SmoothingMode.AntiAlias; //使绘图质量最高，即消除锯齿
            gra.InterpolationMode = InterpolationMode.HighQualityBicubic;
            gra.SmoothingMode = SmoothingMode.HighQuality;
            gra.CompositingQuality = CompositingQuality.HighQuality;
            gra.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;                     

            gra.DrawImage(bitmap, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);

            gra.Flush();
            gra.Dispose();
            bitmap.Dispose();
            return map;
        }
    }
}
